package com.neu.system.service.impl;

import com.github.pagehelper.Page;
import com.neu.common.exception.UtilException;
import com.neu.system.constant.RedisConstant;
import com.neu.system.domain.NeuAir;
import com.neu.system.domain.NeuAirType;
import com.neu.system.domain.vo.NeuAirVO;
import com.neu.system.mapper.NeuAirMapper;
import com.neu.system.mapper.NeuAirTypeMapper;
import com.neu.system.mapper.NeuCityMapper;
import com.neu.system.service.INeuAirService;

import com.neu.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.neu.common.utils.PageUtils.startPage;

/**
 * 【请填写功能名称】Service业务层处理
 *
 */
@Service
public class NeuAirServiceImpl implements INeuAirService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private NeuAirMapper neuAirMapper;

    @Autowired
    private NeuCityMapper neuCityMapper;

    @Autowired
    private NeuAirTypeMapper neuAirTypeMapper;


    /**
     * 查询【请填写功能名称】
     *
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public NeuAir selectNeuAirById(Long id)
    {
        return neuAirMapper.selectNeuAirById(id);
    }

    @Override
    public NeuAirVO selectNeuAirVoById(Long id)
    {
        NeuAir neuAir = neuAirMapper.selectNeuAirById(id);
        NeuAirVO neuAirVO = airToAirVo(neuAir);
        return neuAirVO;
    }


    @Override
    public List<NeuAirVO> selectNeuAirList(NeuAir neuAir) {

        if (!(neuAir.getQueryCreateTime() == null || neuAir.getQueryCreateTime().equals("Invalid date"))) {
            neuAir.setQueryCreateTime(neuAir.getQueryCreateTime() + "%");
        }

        List<NeuAir> neuAirs = neuAirMapper.selectNeuAirList(neuAir);

        List<NeuAirVO> resultList = new ArrayList<>();
        for (NeuAir air : neuAirs) {
            // 转化为vo
            NeuAirVO neuAirVO = airToAirVo(air);

            resultList.add(neuAirVO);
        }
        return resultList;
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param neuAir 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertNeuAir(NeuAir neuAir)
    {
        Map<String, String> aqi = getAQI(neuAir);
        neuAir.setAirTypeId(Long.valueOf(aqi.get("maxValue")));

        // 判断是否存在当天数据
        NeuAir queue = new NeuAir();
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        // 格式化日期为字符串
        String formattedDate = currentDate.format(formatter);
        queue.setQueryCreateTime(formattedDate + "%");
        queue.setCityId(neuAir.getCityId());
        NeuAir oldAir = neuAirMapper.getCountByQueue(queue);

        System.err.println(oldAir);
        if (oldAir != null) {
            neuAir.setId(oldAir.getId());
            updateNeuAir(neuAir);
            return Math.toIntExact(neuAir.getId());
        }

        redisTemplate.delete(RedisConstant.TODAY_AIR_DATA);
        neuAirMapper.insertNeuAir(neuAir);
        return Math.toIntExact(neuAir.getId());


    }

    private Map<String, String> getAQI(NeuAir neuAir) {
        Map<String, String> map = new HashMap<>();

        Integer coAQI;
        Integer so2AQI;
        Integer pm25AQI;
        try {
            if ("".equals(neuAir.getCo()) || "".equals(neuAir.getSo2()) || "".equals(neuAir.getPm25())
                    || null == neuAir.getCo() || null == neuAir.getSo2() || null == neuAir.getPm25() ) {
                throw new UtilException("数据不能为空");
            }

            double co = Double.parseDouble(neuAir.getCo());
            double so2 = Double.parseDouble(neuAir.getSo2());
            double pm25 = Double.parseDouble(neuAir.getPm25());

            if (co < 0 || so2 < 0 || pm25 < 0) {
                throw new UtilException("请输入正确的格式");
            }

            coAQI = getCoAQI(co);
            so2AQI = getSo2AQI(so2);
            pm25AQI = getPm25AQI(pm25);

        } catch (NumberFormatException e) {
            throw new UtilException("请输入正确的格式");
        }
        int max = coAQI;
        map.put("maxPollutants", "一氧化碳");

        if (so2AQI > max) {
            max = so2AQI;
            map.put("maxPollutants", "二氧化硫");
        }

        if (pm25AQI > max) {
            max = pm25AQI;
            map.put("maxPollutants", "悬浮颗粒物");
        }
        map.put("maxValue", String.valueOf(max));
        return map;
    }

    private Integer getPm25AQI(double pm25) {
        if (pm25 <= 35) {
            return 1;
        } else if (pm25 <= 75) {
            return 2;
        } else if (pm25 <= 115) {
            return 3;
        } else if (pm25 <= 150) {
            return 4;
        } else if (pm25 <= 250) {
            return 5;
        } else if (pm25 <= 500) {
            return 6;
        } else {
            throw new UtilException("请输入正确格式数据");
        }
    }

    private Integer getSo2AQI(double so2) {
        if (so2 <= 50) {
            return 1;
        } else if (so2 <= 150) {
            return 2;
        } else if (so2 <= 475) {
            return 3;
        } else if (so2 <= 800) {
            return 4;
        } else if (so2 <= 1600) {
            return 5;
        } else {
            return 6;
        }
    }

    private Integer getCoAQI(double co) {
        if (co <= 5) {
            return 1;
        } else if (co <= 10) {
            return 2;
        } else if (co <= 35) {
            return 3;
        } else if (co <= 60) {
            return 4;
        } else if (co <= 90) {
            return 5;
        } else if (co <= 150) {
            return 6;
        } else {
            throw new UtilException("请输入正确格式数据");
        }
    }

    private NeuAirVO airToAirVo(NeuAir air) {
        // 查询城市名称
        Long cityId = air.getCityId();
        String cityName = neuCityMapper.selectNeuCityByCityId(cityId);
        // 查询空气质量等级
        NeuAirType neuAirType = neuAirTypeMapper.selectNeuAirTypeById(air.getAirTypeId());

        // 存放数据
        NeuAirVO neuAirVO = new NeuAirVO();
        neuAirVO.setCityId(cityId);
        neuAirVO.setId(air.getId());
        // 设置最大污染物
        Map<String, String> aqi = getAQI(air);
        String maxPollutants = aqi.get("maxPollutants");
        neuAirVO.setMaxPollutants(maxPollutants);
        // 设置城市数据
        neuAirVO.setCityName(cityName);
        // 设置数据数据
        neuAirVO.setCo(air.getCo());
        neuAirVO.setSo2(air.getSo2());
        neuAirVO.setPm25(air.getPm25());
        // 设置类型数据
        neuAirVO.setAqi(neuAirType.getScale());
        neuAirVO.setLevel(neuAirType.getQuality());
        neuAirVO.setAirTypeId(neuAirType.getDescribe());
        neuAirVO.setInfluence(neuAirType.getInfluence());
        neuAirVO.setPropose(neuAirType.getPropose());
        neuAirVO.setColor(neuAirType.getColor());

        neuAirVO.setCreateTime(air.getCreateTime());

        return neuAirVO;
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param neuAir 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateNeuAir(NeuAir neuAir)
    {
        Map<String, String> aqi = getAQI(neuAir);
        neuAir.setAirTypeId(Long.valueOf(aqi.get("maxValue")));

        neuAir.setUpdateTime(DateUtils.getNowDate());
        redisTemplate.delete(RedisConstant.TODAY_AIR_DATA);
        redisTemplate.delete(RedisConstant.TODAY_AIR_DATA + ":" + neuAir.getId());
        return neuAirMapper.updateNeuAir(neuAir);
    }

    /**
     * 批量删除【请填写功能名称】
     *
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteNeuAirByIds(Long[] ids)
    {
        redisTemplate.delete(RedisConstant.TODAY_AIR_DATA);
        for (Long i : ids) {
            redisTemplate.delete(RedisConstant.TODAY_AIR_DATA + ":" + i);
        }
        return neuAirMapper.deleteNeuAirByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     *
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteNeuAirById(Long id)
    {
        redisTemplate.delete(RedisConstant.TODAY_AIR_DATA);
        redisTemplate.delete(RedisConstant.TODAY_AIR_DATA + ":" + id);
        return neuAirMapper.deleteNeuAirById(id);
    }

    @Override
    public Long selectCount(NeuAir neuAir) {
        Long total = neuAirMapper.selectCount(neuAir);
        return total;
    }

    @Override
    public List<NeuAirVO> selectNeuAirListByCity(NeuAir neuAir) {

        List<NeuAir> neuAirs = neuAirMapper.selectNeuAirListByCity(neuAir);

        List<NeuAirVO> resultList = new ArrayList<>();
        for (NeuAir air : neuAirs) {
            // 转化为vo
            NeuAirVO neuAirVO = airToAirVo(air);

            resultList.add(neuAirVO);
        }
        return resultList;
    }

    @Override
    public void test() {
        for (NeuAir neuAir : neuAirMapper.selectNeuAirList(null)) {
            this.updateNeuAir(neuAir);
        }

    }
}
